<template>
  <div class="editShop">
    <Form :model="formItem" :label-width="80" class="shopForm">
      <div class="item-title">基本信息</div>

      <FormItem label="企业名称">
        <Input v-model="formItem.title" placeholder="请输入企业名称" style="width:200px;"></Input>
      </FormItem>
      <!-- <FormItem label="企业logo">
        <div v-if="formItem.logo" class="brand-item-logo disFlex">
          <img :src="formItem.logo">
          <upload :multiple="true" :spread="true" @confirmUpload="changeLogoFn"></upload>
        </div>
        <div
          v-else
          class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
          style="margin: 0;"
        >
          <span>+ 添加图片</span>
          <upload :multiple="true" :spread="true" @confirmUpload="changeLogoFn"></upload>
        </div>
      </FormItem>
      <FormItem label="所属行业">
        <Select v-model="formItem.industry_id" style="width:200px;">
          <Option
            v-for="(item,index) in industry"
            :key="index"
            :value="item.industry_id"
          >{{item.industry_title}}</Option>
        </Select>
      </FormItem>-->
      <FormItem label="企业规模">
        <Select v-model="formItem.scale" style="width:200px;">
          <Option v-for="(item,index) in scaleList" :key="index" :value="item.scale">{{item.value}}</Option>
        </Select>
      </FormItem>
      <FormItem label="企业介绍">
        <Input
          v-model="formItem.description"
          type="textarea"
          :autosize="{minRows: 5,maxRows: 10}"
          placeholder="请输入企业介绍"
          style="width:400px;"
        ></Input>
      </FormItem>
      <FormItem label="地图地址">
        <Input v-model="formItem.address" placeholder="Enter something..." style="width:300px;"></Input>
        <Button
          type="primary"
          @click="openMapFn(cityInfo,'selectCity')"
          style="margin-left:10px"
        >点击选择</Button>
      </FormItem>
      <FormItem label="企业地址">
        <Input v-model="formItem.address" placeholder="请输入企业地址" style="width:300px;"></Input>
        <div>此地址仅用于页面显示，导航地址以地图地址为准</div>
      </FormItem>
      <FormItem label="企业环境">
        <Row>
          <draggable
            class="dragImg"
            v-model="formItem.images"
            :options="{animation: 150}"
            @end="dragEnd"
          >
            <div class="goodsImages" v-for="(item,index) in formItem.images">
              <img
                v-if="item.display_status"
                width="160"
                height="90"
                @click="changeImage(index, 'goods_image', '1280x840')"
                :src="item.image_url"
              />
              <a
                v-if="item.display_status"
                class="close-modal small"
                @click.stop="removeGoodsImage(index)"
              >x</a>
            </div>
          </draggable>
          <div style="display: none">
            <upload ref="uploadTool" @confirmUpload="getSingleImage"></upload>
          </div>
          <div
            class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
            style="margin: 0;"
          >
            <span>+ 添加图片</span>
            <upload :multiple="true" :spread="true" @confirmUpload="confirmUpload"></upload>
          </div>
        </Row>
      </FormItem>
      <div class="item-title">认证信息</div>
      <FormItem label="资质上传" prop="img">
        <div v-if="formItem.qualification_images.length" class="brand-item-logo disFlex">
          <img :src="formItem.qualification_images[0].auth_image" />
          <!-- <img v-for="(item,index) in formItem.qualification_images" :src="item.auth_image" /> -->
          <upload :multiple="true" :spread="true" @confirmUpload="confirmQliUpload"></upload>
        </div>
        <div
          v-else
          class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
          style="margin: 0;"
        >
          <span>+ 添加图片</span>
          <upload :multiple="true" :spread="true" @confirmUpload="confirmQliUpload"></upload>
        </div>
        <a @click="preview">点击查看大图</a>
      </FormItem>
      <!-- <FormItem label="经营者姓名">
        <Input v-model="formItem.manager_name" placeholder="请输入经营者姓名" style="width:200px;"></Input>
      </FormItem>
      <FormItem label="经营者电话">
        <Input
          v-model="formItem.manager_phone"
          placeholder="请输入经营者电话"
          style="width:200px;"
          @on-blur="checkPhone"
        ></Input>
      </FormItem>-->
      <!-- <FormItem label="创建时间">
        <Input
          v-model="formItem.time_create"
          placeholder="Enter something..."
          disabled
          style="width:200px;"
        ></Input>
      </FormItem>-->
      <FormItem label="绑定用户" style="width:380px;">
        <div style="display:flex;flex-direction:column">
          <span>
            {{formItem.userInfo.phone}}
            <Button
              type="primary"
              :style="formItem.userInfo.phone?'margin-left:50px':'margin-left:0px'"
              @click="showChoiceFn"
            >点击选择</Button>
          </span>
          <span>不绑定用户，企业无法在小程序端管理职位和查看简历</span>
        </div>
      </FormItem>
      <div class="item-title">自定义分享配置</div>
      <Form :model="shareItem" :label-width="120" class="shopForm">
        <FormItem label="分享标题">
          <Input v-model="shareItem.title" placeholder="请输入分享标题" style="width:300px;"></Input>
        </FormItem>
        <FormItem label="H5分享内容">
          <Input v-model="shareItem.h5_content" placeholder="请输入H5分享内容" style="width:300px;"></Input>
        </FormItem>
        <FormItem label="H5分享Icon" prop="img">
          <div v-if="shareItem.h5_icon" class="brand-item-logo disFlex" style="width:125px">
            <img :src="shareItem.h5_icon" />
            <!-- <img v-for="(item,index) in formItem.qualification_images" :src="item.auth_image" /> -->
            <upload :multiple="true" :spread="true" @confirmUpload="changeIcon"></upload>
          </div>
          <div
            v-else
            class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
            style="margin: 0;width:125px"
          >
            <span>+ 添加图片</span>
            <upload :multiple="true" :spread="true" @confirmUpload="changeIcon"></upload>
          </div>
        </FormItem>
        <FormItem label="小程序分享图片" prop="img">
          <div v-if="shareItem.weapp_img" class="brand-item-logo disFlex" style="width:125px">
            <img :src="shareItem.weapp_img" />
            <!-- <img v-for="(item,index) in formItem.qualification_images" :src="item.auth_image" /> -->
            <upload :multiple="true" :spread="true" @confirmUpload="changeImg"></upload>
          </div>
          <div
            v-else
            class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
            style="margin: 0;width:125px"
          >
            <span>+ 添加图片</span>
            <upload :multiple="true" :spread="true" @confirmUpload="changeImg"></upload>
          </div>
        </FormItem>
      </Form>
      <FormItem>
        <Button type="primary" @click="confirm">保存</Button>
        <Button style="margin-left: 8px" @click="back">返回</Button>
      </FormItem>
    </Form>
    <UserSelector ref="userSelector" @confirmChooseFn="confirmChooseFn"></UserSelector>
    <cancellationPeopleModal ref="cancellationPeopleModal" @commitPeopleFn="commitPeopleFn"></cancellationPeopleModal>
    <wxmap ref="wxmap" @commitMapFn="commitMapFn"></wxmap>
  </div>
</template>

<script>
import upload from "base/upload/upload";
import wxmap from "base/map/map";
import cancellationPeopleModal from "base/cancellationPeopleModal/cancellationPeopleModal";
import { CompanyEdit, CompanyCreate, CityInfo } from "api/recuit/bussiness";
import {
  Industry,
  UserSaasSelector,
  Provinces,
  Cities,
  Areas
} from "api/recuit/public";
import UserSelector from "@/components/consumer/userSelector";
import draggable from "vuedraggable";

export default {
  name: "editShop",
  data() {
    return {
      shareItem: {
        id: 3,
        page: "brandInfo",
        name: "商家主页",
        title: "",
        h5_content: "",
        h5_icon: "",
        weapp_img: ""
      },
      formItem: {
        userInfo: {}
      },
      companyId: "",
      industry: [], //行业数据
      scaleList: [
        //企业规模
        // {
        //   scale: 0,
        //   value: "未知"
        // },
        {
          scale: 1,
          value: "10人以下"
        },
        {
          scale: 2,
          value: "10-20人"
        },
        {
          scale: 3,
          value: "20-50人"
        },
        {
          scale: 4,
          value: "50-100人"
        },
        {
          scale: 5,
          value: "100人以上"
        }
      ],
      formItem: {
        address: "",
        user_saas_id: "",
        description: "",
        images: [],
        industry_id: 1,
        industry_title: "餐饮",
        latitude: "",
        logo: "",
        longitude: "",
        manager_name: "",
        manager_phone: "",
        qualification_images: [],
        review_status: 1,
        scale: "",
        time_create: "2019-04-29 10:44:47",
        title: "",
        userInfo: { phone: "", worker_avatar: "", worker_nickname: "" },
        area_id: ""
      },
      cityInfo: {},
      showChoice: false
    };
  },
  components: {
    upload,
    wxmap,
    cancellationPeopleModal,
    UserSelector,
    draggable
  },
  mounted() {
    if (this.$route.params.companyId) {
      let companyId = this.$route.params.companyId;
      this.companyId = companyId;
      CompanyEdit({ companyId: this.companyId }).then(res => {
        if (JSON.stringify(res.userInfo) == "[]") {
          res.userInfo = {
            phone: ""
          };
        }
        this.formItem = res;

        //处理分享配置信息
        if(res.company_transmit_card){
          this.shareItem = JSON.parse(res.company_transmit_card)
        }

        //重组城市信息
        this.cityInfo = Object.assign(
          {
            numPosition: {
              lat: res.latitude,
              lng: res.longitude
            }
          },
          { searchVal: "" },
          res.cityInfo
        );
        // console.log(this.cityInfo)

        // this.formItem.user_saas_id = res.user_saas_id;
      });
    } else {
      CityInfo().then(res => {
        console.log(res);
        //重组城市信息
        this.cityInfo = Object.assign(
          {
            numPosition: {
              lat: 39.92855,
              lng: 116.41637
            }
          },
          { searchVal: "" },
          res
        );
      });
    }
    Industry()
      .then(res => {
        this.industry = res;
      })
      .catch(err => {
        console.log(err);
      });
  },

  methods: {
    preview() {
      window.open(this.formItem.qualification_images[0].auth_image, "_blank");
    },
    changeIcon(_url) {
      this.shareItem.h5_icon = _url[0];
    },
    changeImg(_url) {
      this.shareItem.weapp_img = _url[0];
    },
    //唤起用户选择器
    showChoiceFn() {
      this.$refs.userSelector.openModal(true);
    },
    //选择用户回调
    confirmChooseFn(data) {
      this.formItem.userInfo.phone = data.phone;
      this.formItem.user_saas_id = data.user_saas_id;
      this.$refs.userSelector.openModal(false);
    },
    // 单张图片上传完成的回调
    getSingleImage(arr) {},
    // 图片上传完成之后的回调
    confirmUpload(arr) {
      let images = this.formItem.images;
      for (let i in arr) {
        images.push({ image_url: arr[i], display_status: 1 });
      }
      this.formItem.images = images;
    },
    // 资质图片上传完成之后的回调
    confirmQliUpload(arr) {
      let images = this.formItem.qualification_images;
      for (let i in arr) {
        images.unshift({ auth_image: arr[i], display_status: 1 });
      }
      this.formItem.qualification_images = images;
    },
    // 地图回调
    commitMapFn(_obj, _index) {
      // console.log(_obj)
      this.formItem.latitude = _obj.numPosition.lat;
      this.formItem.longitude = _obj.numPosition.lng;
      this.formItem.address =
        _obj.province + _obj.city + _obj.area + _obj.searchVal;
      this.getAreaId(_obj.province, _obj.city, _obj.area);
    },
    // 打开地图
    openMapFn(_data, _index) {
      this.$refs.wxmap.openFn(_data, _index);
    },
    // 选择人员
    openPeopleFn(_array, _evenName, _index) {
      this.$refs.cancellationPeopleModal.openFn(_array, {
        evenName: _evenName,
        Index: _index
      });
    },
    // 回调事件分发
    commitPeopleFn(_array, _evenData) {
      this[_evenData.evenName](_array, _evenData);
    },
    // 删除图片
    removeGoodsImage(index) {
      let images = this.formItem.images;
      images[index].display_status = 0;
      this.formItem.images = images;
    },
    //删除资质图片
    removeQlImage(index) {
      let images = this.formItem.qualification_images;
      images[index].display_status = 0;
      this.formItem.qualification_images = images;
    },

    //校验必填项
    valiation(value) {
      if (!value.title) {
        this.$Message.error("请输入企业名称");
        return false;
      }
      if (!value.scale) {
        this.$Message.error("请选择企业规模");
        return false;
      }
      if (!value.description) {
        this.$Message.error("请输入企业介绍");
        return false;
      }
      if (!value.latitude || !value.longitude) {
        this.$Message.error("请选择地图地址");
        return false;
      }
      if (!value.address) {
        this.$Message.error("请输入企业地址");
        return false;
      }
      if (!value.area_id) {
        this.$Message.error("请重新选择地图地址");
        return false;
      }
      return true;
    },

    //编辑企业
    confirm() {
      let formItem = this.formItem;
      if (!this.valiation(formItem)) {
        return;
      }
      //数据格式处理和转换
      if (formItem.images.length) {
        for (let i = 0; i < formItem.images.length; i++) {
          typeof formItem.images[i].display_status == "undefined" &&
            (formItem["images[" + i + "][display_status]"] = 1); //图片是否显示 1显示 0隐藏
          typeof formItem.images[i].sequence == "undefined" &&
            (formItem["images[" + i + "][sequence]"] = i);
        }
      }
      if (formItem.qualification_images.length) {
        for (let i = 0; i < formItem.qualification_images.length; i++) {
          typeof formItem.qualification_images[i].display_status ==
            "undefined" &&
            (formItem["qualification_images[" + i + "][display_status]"] = 1); //图片是否显示 1显示 0隐藏
          typeof formItem.qualification_images[i].sequence == "undefined" &&
            (formItem["qualification_images[" + i + "][sequence]"] = i);
        }
      }
      if (this.companyId) {
        formItem.company_id = this.companyId;
      }

      //分享配置处理
      formItem.company_transmit_card = JSON.stringify(this.shareItem);

      if (this.formItem.qualification_images.length > 0) {
        CompanyCreate(formItem)
          .then(res => {
            this.$Message.success("操作成功");
            setTimeout(() => {
              this.$router.push({ name: "shopList" });
            }, 1500);
          })
          .catch(err => {
            this.$Message.error(err);
          });
      } else {
        this.$Message.error("请上传认证资料");
      }
    },
    // 手机号码验证正则
    checkPhone(e) {
      let phone = e.target.value;
      if (phone != "") {
        if (!/^1[34578]\d{9}$/.test(phone)) {
          this.$Message.error("手机号码格式有误");
        } else {
        }
      }
    },
    //获取具体area_id
    getAreaId(province, city, area) {
      let province_code = "";
      let city_code = "";
      let area_code = "";
      Provinces().then(resP => {
        let provinceList = resP.provinces;
        for (let i = 0; i < provinceList.length; i++) {
          if (provinceList[i].name.indexOf(province) > -1) {
            province_code = provinceList[i].code;
          }
        }
        if (province_code) {
          Cities({ provinceCode: province_code }).then(resC => {
            let cityList = resC.cities;
            for (let i = 0; i < cityList.length; i++) {
              if (cityList[i].name.indexOf(city) > -1) {
                city_code = cityList[i].code;
              }
            }
            if (city_code) {
              Areas({ citiesCode: city_code }).then(result => {
                let areasList = result.areas;
                for (let i = 0; i < areasList.length; i++) {
                  if (area == "市辖区") {
                    area_code = areasList[i + 1].code;
                    break;
                  } else if (areasList[i].name.indexOf(area) > -1) {
                    area_code = areasList[i].code;
                  }
                }
                if (area_code != "") {
                  this.formItem.area_id = area_code;
                } else {
                  this.$Message.error("请重新选择地图地址");
                }
              });
            }
          });
        }
      });
    },
    back() {
      this.$router.go(-1);
    },
    //拖拽结束监听事件
    dragEnd(event) {
      // console.log(event)
      // console.log(event.oldIndex)
      // console.log(event.newIndex)
      // console.log(this.formItem.images)

      //互换图片顺序
      this.formItem.images[event.newIndex].sequence = event.newIndex;
      this.formItem.images[event.oldIndex].sequence = event.oldIndex;
      // console.log(this.formItem.images)
    }
  }
};
</script>

<style scoped lang="less">
.editShop {
  padding: 2%;
  background: white;
  .shopForm {
    width: 50%;
    .notice-user {
      padding: 10px;
      box-sizing: border-box;
      border-radius: 5px;
      border: 1px solid #ddd;
      max-width: 292px;
      min-height: 50px;
      min-width: 50px;
      cursor: pointer;

      img {
        float: left;
        margin-left: 10px;
        margin-top: 10px;

        &:nth-of-type(7n + 1) {
          margin-left: 0;
        }

        &:nth-of-type(1),
        &:nth-of-type(2),
        &:nth-of-type(3),
        &:nth-of-type(4),
        &:nth-of-type(5),
        &:nth-of-type(6),
        &:nth-of-type(7) {
          margin-top: 0;
        }
      }
    }
    .item-title {
      margin-bottom: 20px;
      padding: 8px 16px;
      font-weight: bolder;
      background-color: #f5f5f5;
      color: #333;
    }
    .brand-item-logo {
      width: 100px;
      height: 100px;
      padding: 5px;
      border: 1px solid #ddd;
      border-radius: 5px;
      cursor: pointer;
      position: relative;
      top: 0;
      left: 0;

      img {
        width: 100%;
      }
    }

    .dragImg {
      display: flex;
      overflow-x: scroll;
      max-width: 88%;
      margin-right: 12px;
      .goodsImages {
        margin-right: 16px;
        position: relative;

        &:hover {
          cursor: pointer;
          .close-modal {
            display: block;
          }
        }
        .close-modal {
          display: none;
          position: absolute;
          z-index: 2;
          top: 0;
          margin-right: 0;
          right: 0;
          width: 24px;
          height: 24px;
          font-size: 16px;
          line-height: 20px;
          color: #fff;
          text-align: center;
          cursor: pointer;
          background: red;
        }
      }
    }
    .brand-item-environment {
      width: 214px;
      height: 120px;
      padding: 5px;
      border: 1px solid #ddd;
      border-radius: 5px;
      position: relative;
      top: 0;
      left: 0;
      margin-left: 15px;
      overflow: hidden;
      margin-top: 10px;

      &:nth-of-type(2n + 1) {
        margin-left: 0;
      }

      img {
        width: 100%;
        height: 100%;
        float: left;
      }

      & > .close {
        background: red;
        position: absolute;
        top: 0;
        right: 0;
        width: 20px;
        height: 20px;
        cursor: pointer;
        color: #fff;
      }
    }

    .old-brand-item-environment {
      margin-left: 0;
      cursor: pointer;
    }

    .new-add-brand-item-environment {
      padding: 5px;
      border: 1px solid #ddd;
      border-radius: 5px;
      position: relative;
      top: 0;
      left: 0;
      margin-left: 15px;
      overflow: hidden;
      margin-left: 15px;
      cursor: pointer;
      width: 100px;
      height: 100px;
      margin-top: 29px;

      &:nth-of-type(2n + 1) {
        margin-left: 0;
      }

      img {
        width: 100%;
        height: 100%;
        float: left;
      }

      & > .close {
        background: red;
        position: absolute;
        top: 0;
        right: 0;
        width: 20px;
        height: 20px;
        cursor: pointer;
        color: #fff;
      }
    }
  }
  .userImgBlock {
    display: flex;
    align-items: center;
    width: 30%;
    margin-top: 1%;
  }
}
</style>
